package Example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用Synchronized作用于 类和静态方法
 * 结论：作用于这个类的所有对象
 *
 * @author Wang Renlei
 * @Date 2020/7/1
 */

@Slf4j
public class SynchronizedExample2 {

    public static void test1() {
        synchronized (SynchronizedExample2.class) {
            for (int i = 0; i < 10; i++) {
                log.info("test1 - {}", i);
            }
        }
    }


    public static synchronized void test2() {
        for (int i = 0; i < 10; i++) {
            log.info("test2 - {}", i);
        }
    }


    public static void main(String[] args) {
        SynchronizedExample2 example1 = new SynchronizedExample2();
        SynchronizedExample2 example2 = new SynchronizedExample2();
        ExecutorService executorService = Executors.newCachedThreadPool();

        //执行2次
        executorService.execute(() -> {
            example1.test2();
            ;
        });
        executorService.execute(() -> {
            example2.test2();
            ;
        });

        executorService.shutdown();
    }

}
